package cn.com.bluemoon.daps.model.core.file.excel.listener;

import cn.com.bluemoon.daps.common.exception.DapException;
import cn.com.bluemoon.daps.model.core.file.TableData;
import cn.com.bluemoon.daps.model.core.file.config.GlobalParserConfig;
import com.alibaba.druid.DbType;
import com.alibaba.excel.context.AnalysisContext;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 校验
 * 有个很重要的点 DataListener 不能被spring管理，要每次读取excel都要new,然后里面用到spring可以构造方法传进去
 *
 * @author Jarod.Kong
 */
public class TableDataListener extends BaseDataListener<TableData> {
    // WARN: 2021/7/19 新需求要增加导入列时候，需要增加该列，否则无法导入；强制约束模板格式
    private static final HashMap<DbType, String> TABLE_DB_HEADER = new HashMap<DbType, String>(6) {{
        put(DbType.mysql, generateHeadNameStr(Arrays.asList("序号", "表英文名", "表中文名", "表业务描述", "组路径")));
        put(DbType.postgresql, generateHeadNameStr(Arrays.asList("序号", "表英文名", "表中文名", "Schema", "表业务描述", "组路径", "主题", "表分类")));
        put(DbType.hive, generateHeadNameStr(Arrays.asList("序号", "表英文名", "表中文名", "Schema", "表业务描述", "组路径", "主题", "表分类", "stored as", "SERDEPROPERTIES", "TBLPROPERITIES", "LOCATION")));
    }};

    public TableDataListener(GlobalParserConfig globalParserConfig) {
        super(globalParserConfig);
    }

    /**
     * @return 获取数据库对应的表头信息
     */
    @Override
    protected Map<DbType, String> getDbTypeExcelStandardHeader() {
        return TABLE_DB_HEADER;
    }

    @Override
    public void rowDataValidate0(TableData data, AnalysisContext context) {
        // 判断表名是否重复
        String dataKey = generateDataLowCaseKey(data.getTableName());
        data.setKey(dataKey);
        boolean preT = checkExcelRepeatMap.contains(data.getKey());
        if (preT) {
            data.getErrorMsgs().add("表英文名重复");
            data.setFail(true);
            noValidExcelDataCollector.add(data);
        }
    }

    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        DapException dapException = exception instanceof DapException ? ((DapException) exception) : null;
        if (dapException != null) {
            throw new DapException(dapException.getMessage());
        }
        throw exception;
    }
}
